package com.mm.cloth.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.widget.Toast;

import com.mm.cloth.api.ApiClient;
import com.mm.cloth.api.ApiService;
import com.mm.cloth.model.response.ApiResponse;
import com.mm.cloth.model.response.SystemConfigResponse;

/**
 * 更新检查工具类
 * 用于检查应用版本并提示更新
 */
public class UpdateCheckUtil {
    
    /**
     * 检查应用更新
     * @param activity 当前活动
     */
    public static void checkUpdate(final Activity activity) {
        checkUpdate(activity, false);
    }
    
    /**
     * 检查应用更新
     * @param activity 当前活动
     * @param showToast 是否显示检查结果提示
     */
    public static void checkUpdate(final Activity activity, final boolean showToast) {
        ApiService apiService = ApiClient.getInstance().getApiService();
        apiService.getSystemConfig().enqueue(new retrofit2.Callback<ApiResponse<SystemConfigResponse>>() {
            @Override
            public void onResponse(retrofit2.Call<ApiResponse<SystemConfigResponse>> call,
                                 retrofit2.Response<ApiResponse<SystemConfigResponse>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    ApiResponse<SystemConfigResponse> apiResponse = response.body();

                    if (apiResponse.getCode() == 200 && apiResponse.getData() != null) {
                        SystemConfigResponse config = apiResponse.getData();

                        if (config.getVersion() != null) {
                            // 获取当前应用版本
                            String currentVersion = getAppVersionName(activity);

                            // 比较版本号
                            if (compareVersions(config.getVersion(), currentVersion) > 0) {
                                // 有新版本，显示更新对话框
                                showUpdateDialog(activity, config);
                            } else if (showToast) {
                                // 已是最新版本，根据参数决定是否提示
                                Toast.makeText(activity, "当前已是最新版本", Toast.LENGTH_SHORT).show();
                            }
                        }
                    } else if (showToast) {
                        Toast.makeText(activity, "检查更新失败", Toast.LENGTH_SHORT).show();
                    }
                } else if (showToast) {
                    Toast.makeText(activity, "检查更新失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(retrofit2.Call<ApiResponse<SystemConfigResponse>> call, Throwable t) {
                if (showToast) {
                    Toast.makeText(activity, "检查更新失败: " + t.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    
    /**
     * 显示更新对话框
     * @param activity 当前活动
     * @param config 系统配置信息
     */
    private static void showUpdateDialog(final Activity activity, final SystemConfigResponse config) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("发现新版本");
        builder.setMessage("发现新版本 " + config.getVersion() + "\n\n" + config.getUpdateLog());
        
        // 设置更新按钮
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 打开浏览器下载
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(config.getDownloadUrl()));
                    activity.startActivity(intent);
                } catch (Exception e) {
                    Toast.makeText(activity, "无法打开下载链接", Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        // 如果不是强制更新，添加取消按钮
        if (!config.isForceUpdate()) {
            builder.setNegativeButton("稍后再说", null);
        } else {
            // 强制更新时不允许取消对话框
            builder.setCancelable(false);
        }
        
        builder.show();
    }
    
    /**
     * 获取应用版本名称
     * @param context 上下文
     * @return 版本名称
     */
    private static String getAppVersionName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
            return packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "1.0.0"; // 默认版本
        }
    }
    
    /**
     * 比较两个版本号
     * @param version1 版本1
     * @param version2 版本2
     * @return 大于0表示version1大于version2，等于0表示相等，小于0表示version1小于version2
     */
    private static int compareVersions(String version1, String version2) {
        String[] parts1 = version1.split("\\.");
        String[] parts2 = version2.split("\\.");
        
        int length = Math.max(parts1.length, parts2.length);
        
        for (int i = 0; i < length; i++) {
            int v1 = (i < parts1.length) ? Integer.parseInt(parts1[i]) : 0;
            int v2 = (i < parts2.length) ? Integer.parseInt(parts2[i]) : 0;
            
            if (v1 != v2) {
                return v1 - v2;
            }
        }
        
        return 0;
    }
} 